<template>
<div id="code-dict-manage">
  <v-header title="代码字典" :showDownloadBtn = "download" :saveShow = "save"></v-header>
  <el-container class="code-dict-manage-box">
    <el-header class="header-tool-bar">
      <!-- 按钮 -->
      <el-row>
        <el-button type="primary" size="mini" @click="adddialogForm">增加</el-button>
        <el-button type="primary" size="mini" @click.stop="removedata">删除</el-button>
        <el-button type="primary" size="mini" @click="handleEdit">编辑</el-button>
        <el-button type="primary" size="mini" @click="refresh">刷新</el-button>
        <span class="condition-query">
          <el-input v-model="condition" size="mini" prefix-icon="el-icon-search" placeholder="请输入内容"
                    clearable></el-input>
          <el-button type="primary" size="mini" @click="queryForPage">查询</el-button>
        </span>
      </el-row>
    </el-header>
    <el-main class="main-table-box">
      <!-- 表单 -->
      <el-table
        ref="table"
        :data="tableData"
        @selection-change="handleSelectionChange"
        @select="checkrow"
        v-loading="tableLoading"
        v-model="checked"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="auto">
        </el-table-column>
        <el-table-column
          prop="code_id"
          label="代码ID"
          width="auto">
        </el-table-column>
        <el-table-column
          prop="code_value"
          label="代码取值"
          width="auto">
        </el-table-column>
        <el-table-column
          prop="code_value_nm_ens"
          label="代码取值英文含义"
          width="auto">
        </el-table-column>
        <el-table-column
          prop="code_value_nm_cns"
          label="代码取值中文含义"
          width="auto">
        </el-table-column>
        <el-table-column
          prop="code_state"
          label="代码管理状态"
          :formatter="formatcodestate"
          width="auto">
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
        </el-pagination>
    </el-main>
  </el-container>
  <!-- 新增/编辑弹窗 -->
    <el-dialog :title="addRoleDialogMode === 'ADD' ? '新增数据' : '编辑数据'"
               :visible.sync="addRoleDialogVisiable"
               v-model="addRoleDialogMode"
               @close="cancel"
               >
      <el-form :model="ruleForm" :rules="rules"  ref="ruleForm" label-width="180px"  class="demo-ruleForm">
        <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="代码ID" prop="code_id">
          <el-input v-model="ruleForm.code_id" :disabled="editcodeid"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代码取值" prop="code_value">
          <el-input v-model="ruleForm.code_value" :disabled="editcodevalue"></el-input>
        </el-form-item>
        </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="代码取值英文含义" prop="code_value_nm_ens">
            <el-input v-model="ruleForm.code_value_nm_ens"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代码取值中文含义" prop="code_value_nm_cns">
              <el-input v-model="ruleForm.code_value_nm_cns"></el-input>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="代码取值英文使用说明" prop="code_value_use_ens">
            <el-input v-model="ruleForm.code_value_use_ens"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代码取值中文使用说明" prop="code_value_use_cns">
              <el-input v-model="ruleForm.code_value_use_cns"></el-input>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="代码管理状态" prop="code_state">
            <el-select v-model="ruleForm.code_state" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24" class="btn-center">
            <el-form-item class="dialogbtn">
              <el-button @click="resetForm('ruleForm')" >重置</el-button>
              <el-button @click="cancel">关闭</el-button>
              <el-button type="primary" @click="submitForm('ruleForm')" >确定</el-button>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
</div>
</template>

<script>
  import { VHeader } from '../../../../components'
  import ajax from '../../../../api/ajax/ajax'
  import api from '../../../../api/url'
  import { numLetteValidator } from '../../../../assets/js/rules'
export default{
  name: 'codedict-manage',
  components: {
    VHeader
  },
  data () {
      return {
        // 代码状态管理
        options: [{
          value: '0',
          label: '无效'
        }, {
          value: '1',
          label: '有效'
        }],
        tableLoading: true,
        condition: '', // 输入条件
        addRoleDialogVisiable: false,
        editdialogform: false,
        currentPage: 1, // 当前页码
        pagesize: 10, // 默认每页数据量
        totalCount: 0, // 默认数据总数
        editcodeid: false,
        editcodevalue: false,
        checked: false,
        // te_date: '',
        // le_date: '',
        tableData: [],
        checkbox: [],
        addRoleDialogMode: 'ADD', // 对话框色对话框模式  ADD新增 MODIFY 修改
        list: [],
        download: false,
        save: false,
        ruleForm: {
          code_id: '',
          code_value: '',
          code_value_nm_ens: '',
          code_value_nm_cns: '',
          code_value_use_ens: '',
          code_value_use_cns: '',
          code_state: '',
          level_id: ''
        },
        rules: {
          code_id: [
            { required: true, message: '请输入', trigger: 'blur' },
            { max: 7, message: '最多输入7个字符', trigger: 'blur' },
            { validator: numLetteValidator, trigger: 'blur' }
          ],
          code_value: [
            { required: true, message: '请输入', trigger: 'blur' },
            { max: 20, message: '最多输入20个字符', trigger: 'blur' },
            { validator: numLetteValidator, trigger: 'blur' }
          ],
          code_value_nm_ens: [
            { required: true, message: '请输入', trigger: 'blur' },
            { max: 60, message: '最多输入60个字符', trigger: 'blur' }
          ],
          code_value_nm_cns: [
            { required: true, message: '请输入', trigger: 'blur' },
            { max: 60, message: '最多输入60个字符', trigger: 'blur' }
          ],
          code_value_use_ens: [
            { required: true, message: '请输入', trigger: 'blur' },
            { max: 100, message: '最多输入100个字符', trigger: 'blur' }
          ],
          code_value_use_cns: [
            { required: true, message: '请输入', trigger: 'blur' },
            { max: 100, message: '最多输入100个字符', trigger: 'blur' }
          ],
          code_state: [
            { required: true, message: '请选择', trigger: 'blur' }
          ]
        }
      }
    },
    created () {
      this.queryForPage()
    },
    methods: {
      formatcodestate (row, column) {
        return row.code_state === '1' ? '有效' : '无效'
      },
      resetForm () {
        this.$refs.ruleForm.clearValidate()
        this.ruleForm = {...this.currentItem}
      },
      // 每页显示条目个数
      handleSizeChange (val) {
        this.pagesize = val
        this.handleCurrentChange()
      },
      queryForPage () {
        const pagelistdata = {
        keyword: this.condition,
        pageNo: this.currentPage,
        pageSize: this.pagesize
        }
        ajax.post(api.SELECT_METACODEDICT_LIST_FOR_PAGE, pagelistdata).then((res) => {
          this.tableLoading = false
          this.tableData = []
          this.tableData = res.data.list
          this.totalCount = res.data.total
          this.checked = false // 清除选中状态
        })
      },

      // 当前页数
      handleCurrentChange (val) {
        this.currentPage = val
        this.queryForPage()
      },
      adddialogForm () {
        this.ruleForm = {}
        this.currentItem = {}
        this.$refs.table.clearSelection() // 点击新增清除选中状态
        this.checked = false
        this.addRoleDialogVisiable = true
        this.addRoleDialogMode = 'ADD'
        this.editcodeid = false
        this.editcodevalue = false
      },
      cancel () {
        this.$refs.ruleForm.clearValidate()
        this.ruleForm = {...this.currentItem}
        this.$refs.ruleForm.resetFields() // 移除校验 重置为初始状态
        this.addRoleDialogVisiable = false
        this.editdialogform = false
      },
      removedata () {
        if (this.list.length > 0) {
          this.$confirm('是否删除所选记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let remdata = {
              key_list: this.list
            }
            ajax.post(api.DELETE_METACODEDICT, remdata).then((res) => {
              this.handleSizeChange()
            })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // })
          })
        } else {
          this.$message.error('请选择一条记录进行删除')
        }
      },
      handleSelectionChange (val) {
        this.list = []
        for (let i = 0; i < val.length; i++) {
          let remdata = {
            code_id: val[i].code_id,
            code_value: val[i].code_value
          }
          this.list.push(remdata)
        }
      },
      checkrow (row) {
        if (row.length > 0) {
          this.ruleForm = row[0]
          this.checkbox = row
          this.checked = true
        } else {
          this.checked = false
        }
      },
      handleEdit (row) {
        if (this.checked === true) {
          if (this.list.length < 2) {
            this.addRoleDialogVisiable = true // 显示弹框
            this.editcodeid = true
            this.editcodevalue = true
            this.addRoleDialogMode = 'MODIFY' // 新增角色对话框模式 编辑模式
            // this.ruleForm.date = [this.setTime(this.ruleForm.te_date), this.setTime(this.ruleForm.le_date)]
            // 定义变量接收一下当前对象
            this.currentItem = JSON.parse(JSON.stringify(this.ruleForm))
            // 解除双向绑定
            this.ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
          } else {
            this.$message.error('只能选择一条')
          }
        } else {
          this.$message.error('请选择一条记录进行编辑')
        }
      },
      refresh () {
        this.handleSizeChange()
      },
      // // 获取日期
      // getdate (list) {
      //   if (list) {
      //     this.te_date = getDateTime(list[0], 's').replace(/^(\d{8})(\d{6})$/, '$1')
      //     this.le_date = getDateTime(list[1], 's').replace(/^(\d{8})(\d{6})$/, '$1')
      //   } else {
      //     this.te_date = ''
      //     this.le_date = ''
      //   }
      // },
      // // 时间反显格式化
      // setTime (s) {
      //   let dateList = ''
      //   let arr = s.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1,$2,$3').split(',')
      //   dateList = (new Date(new Date().setFullYear(Number(arr[0]), Number(arr[1]) - 1, Number(arr[2]))))
      //   return dateList
      // },
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const insertdata = {
              code_id: this.ruleForm.code_id,
              code_value: this.ruleForm.code_value,
              code_value_nm_ens: this.ruleForm.code_value_nm_ens,
              code_value_nm_cns: this.ruleForm.code_value_nm_cns,
              code_value_use_ens: this.ruleForm.code_value_use_ens,
              code_value_use_cns: this.ruleForm.code_value_use_cns,
              code_state: this.ruleForm.code_state
              // te_date: this.te_date,
              // le_date: this.le_date
            }
            if (this.addRoleDialogMode === 'ADD') {
              // 新增接口
              ajax.post(api.INSERT_METACODEDICT, insertdata).then((res) => {
                this.handleSizeChange()
              })
            } else if (this.addRoleDialogMode === 'MODIFY') {
              // 修改接口
              ajax.post(api.UPDATE_METACODEDICT, insertdata).then((res) => {
                this.ruleForm = {}
                this.handleSizeChange()
              })
            }
            this.addRoleDialogVisiable = false
            if (this.addRoleDialogMode === 'ADD') {
              this.$message({
              type: 'success',
              message: '新增成功!'
            })
            } else {
              this.$message({
              type: 'success',
              message: '编辑成功!'
            })
            }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #code-dict-manage
    height 100%
    position relative
    .code-dict-manage-box
      height 100%
      padding 10px 0px 20px 10px
      .header-tool-bar
        line-height 50px
        vert-align middle
        background-color #FFFFFF
        margin-bottom 3px
        .condition-query
          width 300px
          float right
          margin-right -10px
        .el-input--mini
          width 200px
        .el-button--danger
          background-color #016DFB
          border-color #016DFB
        .dialog-input
          width 210px
          height 30px
          border-radius 4px
          border 1px solid #D8DCE5
      .main-table-box
        padding 0px 0px
        height 100%
        background-color #fff
        .el-table
          padding-bottom 74px
        .el-pagination
          z-index 5
          height 36px
          background-color #fff
          position absolute
          width 100%
          bottom 0px
          padding-bottom 4px
          border-top solid 1px #f4f4f4
    .el-dialog
      width 900px
      padding-right 20px
      .el-dialog__body
        margin 0 auto
        padding 20px 20px
        .el-input
          width 100%
          .el-input__inner
            height 40px
        .el-select
          width 228px
          height 40px
        .btn-center
          text-align right
</style>
